<template>
  <div>
    <el-upload
      v-loading="loading"
      action="/"
      :file-list="fileList"
      v-bind="props"
      :list-type="props['list-type'] || 'picture-card'"
      :http-request="events['http-request'] ||uploadFile"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      v-on="events"
    >
      <el-button v-if="props['list-type'] && props['list-type']=== 'text'" type="primary" icon="el-icon-plus">选择文件</el-button>
      <i v-else class="el-icon-plus" />
    </el-upload>
  </div>
</template>

<script>
import BasicQiniuApi from '@/api/basic/qiniu'
import * as qiniu from 'qiniu-js'
export default {
  name: 'AllenUpload',
  props: {
    value: {
      type: String,
      required: false,
      default: ''
    },
    props: {
      type: Object,
      required: false,
      default: () => ({})
    },
    events: {
      type: Object,
      required: false,
      default: () => ({})
    }
  },
  data() {
    return {
      uid: 0,
      loading: false,
      qiniuConfig: {
        token: '',
        domain: '',
        fileName: ''
      }
    }
  },
  computed: {
    modelValue: {
      get() {
        return this.value ? this.value.split(',') : []
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    fileList() {
      const arr = []
      this.modelValue.forEach(element => {
        arr.push({
          name: element,
          url: element
        })
      })
      return arr
    }
  },
  created() {
    this.getUpToken()
  },
  methods: {
    getUpToken() {
      BasicQiniuApi.getToken().then(res => {
        this.qiniuConfig = res.data
      })
    },
    beforeUpload() {
      this.loading = true
    },
    uploadFile(event) {
      this.uid++
      const fileSubFix = event.file.name.substr(event.file.name.lastIndexOf('.'))
      const uploadPath = event.file.name.replace(fileSubFix, '-') + this.qiniuConfig.fileName + '-' + this.uid + fileSubFix
      const _this = this
      const observer = {
        complete(res) {
          if (_this.props.multiple === true) {
            if (_this.modelValue.length === 0) {
              _this.modelValue = _this.qiniuConfig.domain + '/' + res.key
            } else {
              _this.modelValue = _this.value + ',' + _this.qiniuConfig.domain + '/' + res.key
            }
          } else {
            _this.modelValue = _this.qiniuConfig.domain + '/' + res.key
          }
          _this.loading = false
        }
      }
      const observable = qiniu.upload(event.file, uploadPath, this.qiniuConfig.token, null, { useCdnDomain: true })
      observable.subscribe(observer)
    },
    handleRemove(file, fileList) {
      this.$emit('input', fileList.map(ele => ele.url).join(','))
    }
  }
}
</script>

<style>

</style>
